<template>
  <div class="importC">
    <el-dialog
      title="用户文件上传下载"
      v-bind="$attrs"
      v-on="$listeners"
      :visible.sync="visible"
      class="dialogC"
      :before-close="handleClose"
      @close="onClose">
      <el-row :gutter="15" label-width="100px">
          <el-col :span="12">
            <input class="file" type="file" title="请选择上传文件" value="请选择上传文件">
          </el-col>
          <el-col :span="12">
            <button class="submit" @click="upload">上传</button>
          </el-col>
      </el-row>
      <el-row :gutter="15" label-width="100px">
        <el-col :span="24">
          <button class="uploadModle" @click="downloadModle">下载模板</button>
        </el-col>
      </el-row>
      <div slot="footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="visible = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {exportUsers} from '@/api/users'
import {mImportUsers} from '@/api/users'

var formData = new window.FormData() // vue 中使用此方法创建FromData对象 window.FormData(),否则会报 'FormData isn't definded'


export default {
  name: 'mImportExcel',
  props:{
    dialogVisible:{
      type:Boolean,
      default: false
    }
  },
  data() {
    return {
      visible: false,
      userVO:{
        isUploadModel:'1'
      },
      name: ''
    };
  },
  watch:{
    dialogVisible(){
      this.visible = this.dialogVisible
    }
  },
  methods: {
    upload(){
      formData.append('file', document.querySelector('input[type=file]').files[0]) // 'file' 这个名字要和后台获取文件的名字一样;
      formData.append('user',this.name)
      //'userfile'是formData这个对象的键名
      mImportUsers(formData).then((res) => {
        console.log(res);
      },error => {
        console.log(error);
      }) // 发送请求

    },
    downloadModle(){
      exportUsers(this.userVO).then(res => {
        this.btnLoading = false;
        console.log("res")
        console.log(res)
        if (res.data.type) {
          // 文件下载
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel"
          });
          let link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.setAttribute('download', '导出文件.xlsx');
          link.click();
          link = null;
          this.$message.success('导出成功');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消导出'
        });
      });
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.onClose()
        })
        .catch(_ => {});
    },
    onClose(){
      console.log("Close");
      this.close()
    },
    close(){
      this.visible = false
      this.$emit('UpDateImportVisible', false)
    }
  }
}
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}
.el-col {
  border-radius: 4px;
}
.importC{
  width: 100%;
  height: 100%;
}
</style>
